<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <style>
      * {
        margin: 0;
        padding: 0;
        background-color: #333;
      }
    </style>
  </head>
  <body>
    <script>
      const obj = {
        title: 'hello',
        age: 18,
      };

      // 监听所有的属性
      for (const key of Object.keys(obj)) {
        let value = obj[key];
        Object.defineProperty(obj, key, {
          get() {
            console.log(`监听到:获取${key}值`);
            return value;
          },
          set(newValue) {
            console.log(`监听到${key}变化`);
            value = newValue;
          },
        });
      }

      console.log(obj.title);
      obj.title = 'world';
      console.log(obj.age);
      obj.age = 12;
    </script>
  </body>
</html>
